package http

import (
	"context"
	"fmt"
	"io"
	"net/http"
	// "gcp-api-proxy/pkg/util"
)

func DefaultHandlerFunc[T any, V any](defaultHandler *DefaultHandler[T, V]) func(http.ResponseWriter, *http.Request) {
	return func(writer http.ResponseWriter, req *http.Request) {
		fmt.Println("--------before doProcess-------")
		doProcess(writer, req, defaultHandler)
	}
}

func doProcess(writer http.ResponseWriter, req *http.Request, reqHandler IReqHandler) {
	// 转换http请求对象为标准请求对象
	ctx := context.Background()
	baseReq, err := translate(ctx, req)
	if err != nil {
		writer.WriteHeader(http.StatusInternalServerError)
		writer.Write([]byte(err.Error()))
		return
	}

	// 处理请求
	baseResp := reqHandler.Handle(ctx, baseReq)

	// 回写结果
	err = write(ctx, writer, baseResp)
	if err != nil {
		reqHandler.GetLogger().Error(ctx, fmt.Sprintf("write resp result error:%s", err.Error()))
	}
}

func write(ctx context.Context, writer http.ResponseWriter, baseResp *BaseResp) error {
	writer.WriteHeader(baseResp.StatusCode)
	for k, vs := range baseResp.Header {
		for _, v := range vs {
			writer.Header().Add(k, v)
		}
	}

	if len(baseResp.Body) > 0 {
		_, err := writer.Write(baseResp.Body)
		return err
	}
	return nil
}

func translate(ctx context.Context, req *http.Request) (*BaseReq, error) {
	// req.Body = io.NopCloser(util.ReusableReader(req.Body))
	rawBody, err := io.ReadAll(req.Body)
	if err != nil {
		return nil, err
	}
	baseReq := &BaseReq{
		Header:     req.Header,
		Body:       rawBody,
		RequestURI: req.RequestURI,
	}
	return baseReq, nil
}
